/*!
 * tykhome - tag.js
 * Author tykhome <yongketian@gmail.com>
 */

/**
 * Module dependencies.
 */
var Soft = require('../proxy').Soft;
var SoftTag = require('../proxy').SoftTag;
var Tag = require('../proxy').Tag;

var EventProxy = require('eventproxy');

exports.list = function (req, res, next) {
	console.log('soft.tag');

	var proxy = EventProxy.create('tags', 'tag_cloud',
		function (tags, tag_cloud) {
			res.render('soft/tag', {
				tags: tags,
				tag_cloud: tag_cloud
			});
		}
	).fail(next);;

	var query = {
		soft_count: {
			'$gt': 0
		}
	};
	var opt = {
		sort: {
			soft_count: -1
		}
	};
	Tag.getTagsByQuery(query, {}, opt, proxy.done(function (tags) {
		if (!tags) proxy.emit('tags', []);

		var tags_done = function (tags) {
			// console.log(tags);
			proxy.emit('tags', tags);
		};
		// after重复异步协作 重复保存
		proxy.after('tag', tags.length, tags_done);
		tags.forEach(function (tag) {
			SoftTag.getSoftTagByTagId(tag._id, proxy.done(function (soft_tags) {
				if (!soft_tags) {
					tag.softs = [];
					proxy.emit('tag', tag);
				}

				var softIds = [];
				soft_tags.forEach(function (soft_tag) {
					softIds.push(soft_tag.soft_id);
				});
				Soft.getSoftByIds(softIds, {
					_id: 1,
					title: 1
				}, {}, proxy.done(function (softs) {
					tag.softs = softs || [];
					proxy.emit('tag', tag);
				}));

			}));
		});

	}));

	var options = {
		sort: {
			soft_count: -1
		}
	};
	Tag.getTagsByQuery(query, {}, options, proxy.done('tag_cloud'));
};